package opencv.utils;

import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;

public class InitUtils {

    private static final Logger log = LoggerFactory.getLogger(InitUtils.class);

    /**
     *自动添加动态库
     */
    public static void addLibrary() {
        try {
            addDir(new File("./lib/library").getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 添加动态库位置   java.library.path添加不起作用，因为java.library.path只在jvm启动时读取一次，其他情况下的修改不会起作用的
     * 源码
     *     *   if (sys_paths == null) {
     *            usr_paths = initializePath("java.library.path");
     *           sys_paths = initializePath("sun.boot.library.path");
     *        }
     * @param s
     * @throws IOException
     */
    public static boolean addDir(String s) {
        try {
            Field field = ClassLoader.class.getDeclaredField("usr_paths");
            field.setAccessible(true);
            String[] paths = (String[])field.get(null);
            for (int i = 0; i < paths.length; i++) {
                if (s.equals(paths[i])) {
                    return true;
                }
            }
            String[] tmp = new String[paths.length+1];
            System.arraycopy(paths,0,tmp,0,paths.length);
            tmp[paths.length] = s;
            field.set(null,tmp);
            return true;
        } catch (Exception e) {
            log.error("Failed to get field handle to set library path");
        }
        return false;
    }
}
